<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>发票管理</title>
    <link rel="stylesheet" href="../static/layui/css/layui.css">
</head>

<body >
    <div class="layui-fluid" style="padding: 15px;">
        <ul class="layui-nav" style="text-align: right;">
            <button data-method="notice" class="layui-btn layui-btn-sm" onclick="notice();">问题记录</button>
            <li class="layui-nav-item">
              <a href="">电子发票识别工具</a>
            </li>
        </ul>
        <div class="demoTable" style="text-align: left; margin-top: 7px; margin-right: 15px;">
            归属人姓名：
            <div class="layui-inline">
                <input class="layui-input" name="userName" id="searchValue" autocomplete="off">
            </div>
            <button class="layui-btn layui-btn-sm" onclick="search();">搜索</button>
        </div>
        <div class="layui-row">
            <table class="layui-hide" id="ticket-crud" lay-filter="ticket-filter"></table>
            <div id="pageDiv"></div>
        </div>
    </div>

<!--编辑表单-->
<div class="layui-row" id="uploadTicket" style="display:none;">
    <div class="layui-col-md10">
        <form class="layui-form layui-from-pane" id="saveTicket" style="margin-top:20px" action="#"
              enctype="multipart/form-data">

            <div class="layui-form-item">
                <label class="layui-form-label">组名</label>
                <div class="layui-input-inline">
                    <input placeholder="请在下拉框中选择组名" name="groupName" id="groupNameId" required lay-verify="required" autocomplete="off"
                           class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">员工信息</label>
                <div class="layui-input-inline">
                    <input placeholder="请在下拉框中选择员工信息" name="userInfo" id="userInfoId" required lay-verify="required"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">

                <div class="layui-input-block">
                    <div class="layui-upload-drag" id="fileshow">
                        <i class="layui-icon"></i>
                        <p>点击上传，*不支持*文件拖拽到此处</p>
                        <div class="layui-hide" id="uploadDemoView">
                            <hr>
                            <img src="" alt="上传成功后渲染" style="max-width: 100%">
                        </div>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit="" id="upload-btn" lay-filter="upload-btn">提交
                    </button>
                </div>
            </div>

        </form>
    </div>
</div>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="upload"><i class="layui-icon">&#xe608;</i>上传发票</button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="remove"><i class="layui-icon">&#xe640;</i>批量删除</button>
        <button class="layui-btn layui-btn-sm " lay-event="downPdf"><i class="layui-icon">&#xe608;</i>批量下载PDF</button>
        <button class="layui-btn layui-btn-sm " lay-event="downExcel"><i class="layui-icon">&#xe608;</i>批量下载EXCEL</button>
    </div>
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>


<script src="../static/common/js/jquery-3.3.1.min.js"></script>
<script src="../static/layui/layui.js" charset="utf-8"></script>
<script src="../static/common/js/ajax.js"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->

<script>
    var table;
    var upload; //上传
    var form;
    var laypage;
    var pageCurr = 1;
    var pageLimit = 10;
    var itemCount;
    var dropdown;

  layui.use('table', function () {
    table = layui.table;
    upload = layui.upload; //上传
    form = layui.form;
    laypage = layui.laypage;
    dropdown  = layui.dropdown;

    
    AsyncGet("/api/v1/invoice",{"page":pageCurr,"limit":10},function (data, request) {
        initTableByData(data);
        if(localStorage.token==null){
            localStorage.token=request.getResponseHeader("Authorization");
        }
        if(localStorage.token==="null"){
            localStorage.token=request.getResponseHeader("Authorization");
        }
    })    

    //工具栏事件
    table.on('toolbar(ticket-filter)', function (obj) {
        const checkStatus = table.checkStatus(obj.config.id);
        var data = checkStatus.data;
        switch (obj.event) {
          // 新增
        case 'upload':
          layer.open({
            type: 1,
            offset: '10px',
            title: "上传发票文件",
            area: ['500px', '450px'],
            content: $("#uploadTicket")
          });
          break;
        case 'remove':
            if (data.length === 0) {
                layer.msg('请选择一行');
            } else {
                layer.confirm('真的删除么', function(){
                    batchRemove(data);
                });
            }
          break;
        case 'downPdf':
            if (data.length === 0) {
                layer.msg('请选择一行');
            } else {
                layer.confirm('仅支持下载识别成功的发票！确认下载么', function() {
                    batchDownPdf(data);
                });
            }
          break;
        case 'downExcel':
            if (data.length === 0) {
                layer.msg('请选择一行');
            } else {
                layer.confirm('仅支持下载识别成功的发票！确认下载么', function() {
                    batchDownExcel(data);
                });
            }
          break;
      }
    });

      initGroupDropdownByData();

      upload.render({
          elem: '#fileshow'
          , accept: 'file'
          , exts: 'pdf'
          , auto: false
          , multiple: true
      });

          //监听提交
    form.on('submit(upload-btn)', function(data){
        const formSatellite = document.getElementById("saveTicket");//获取所要提交form的id
        const fs1 = new FormData(formSatellite);  //用所要提交form做参数建立一个formdata对象
        SyncPost("/api/v1/invoice/upload", fs1, function (data) {
            if (data.code === 0) {
                layer.msg(data.msg, closeAndReloadTable(null));
            } else {
                layer.msg("上传失败："+data.msg, closeAndReloadTable(null));
            }
        });
        return false;
    });

    //监听行工具事件
    table.on('tool(ticket-filter)', function(obj){
        var data = obj.data;
        //console.log(obj)
        if(obj.event === 'del'){
            layer.confirm('真的删除么', function(index){
                remove(data);
            });
        }
    });

});

  function notice() {
      //示范一个公告层
      layer.open({
          type: 1
          ,title: false //不显示标题栏
          ,closeBtn: false
          ,area: '400px;'
          ,shade: 0.8
          ,id: 'LAY_layuipro' //设定一个id，防止重复弹出
          ,btn: ['火速围观', '工具不错']
          ,btnAlign: 'c'
          ,moveType: 1 //拖拽模式，0或者1
          ,content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">你知道吗？亲！<br>发票识别工具仅支持PDF格式，PDF格式的发票文件通常只有40K<br>' +
              '<br> 常规使用步骤：<br>1，点击【上传发票】后上传发票（当前不支持拖拽的方式实现）；<br>2，点击【批量下载PDF文件】，目的是获取修改了原始发票的文件名的PDF文件；<br>3，点击【批量下载EXCEL】，目的是获取填写《增值税普通导入模板》后的EXCEL文件 <br>' +
              '<br>发票识别工具是基于layui和pdf-box开发，但仍有其他未知问题，欢迎通过【火速围观】反馈，也可邮箱反馈*test@test.com* ^_^</div>'
          ,success: function(layero){
              var btn = layero.find('.layui-layer-btn');
              btn.find('.layui-layer-btn0').attr({
                  href: 'https://demo.com'
                  ,target: '_blank'
              });
          }
      });
  }

    function search() {
            reloadTable(null);
    }

    function reloadTable(userName) {
        if(userName==null){
            userName = $("#searchValue").val();
        }
        //执行重载
        AsyncGet("/api/v1/invoice",{"page":pageCurr,"limit":pageLimit, "userName":userName},function (data, request) {
            initTableByData(data);
            if(localStorage.token==null){
                localStorage.token=request.getResponseHeader("Authorization");
            }
            if(localStorage.token==="null"){
                localStorage.token=request.getResponseHeader("Authorization");
            }
        })
      }

    //温馨提示：默认由前端自动合计当前行数据。从 layui 2.5.6 开始： 若接口直接返回了合计行数据，则优先读取接口合计行数据。
    //详见：https://www.layui.com/doc/modules/table.html#totalRow
    function initTableByData(obj){
        data = obj.data;
        itemCount = obj.count;
        tableIns=table.render({
        elem: '#ticket-crud'
        , data: data
        , limit: pageLimit
        , toolbar: '#toolbarDemo'
        , defaultToolbar: ['filter']
        , title: '发票数据表'
        , totalRow: true
        , cols: [
            [
            {type: 'checkbox', fixed: 'left'}
            , {field: 'code', title: '发票代码', width: 130, totalRowText: '合计'}
            , {field: 'number', title: '发票号码', width: 100}
            , {field: 'date', title: '发票日期', width: 120}
            , {field: 'checkNum', title: '校验码后六位', width: 120}
            , {field: 'userName', title: '归属人', width: 80}
            , {field: 'total', title: '发票金额', width: 100, totalRow: true}
            , {field: 'groupName', title: '部门', width: 100}
            , {field: 'message', title: '识别失败原因', width: 150}
            , {field: 'taxCode', title: '购方税号', width: 120}
            , {field: 'createdAt', title: '上传时间', width: 150}
            , {field: 'id', title: 'ID', width: 120}
            , {fixed: 'right', field: 'success', title: '成功', width: 80, sort: true}
            , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 80}
            ]
        ]
        , id: 'testReload'
        , page: false
        , done: function(res, curr, count){
            laypageReload();
        }
        });
    }

    function laypageReload(){
        //执行一个laypage实例
        laypage.render({
            elem: 'pageDiv' //注意，这里的 test1 是 ID，不用加 # 号
            ,count: itemCount //数据总数，从服务端得到
            ,limit: pageLimit //每页的行数
            ,curr: pageCurr //分页数据
            ,layout: ['count', 'prev', 'page', 'next', 'limit']
            ,jump: function(obj, first){
                pageCurr = obj.curr;
                pageLimit = obj.limit;
                
                //首次不执行
                if(!first){
                    reloadTable(null);
                }
            }
        });
    }

    function closeAndReloadTable(userName) {
        layer.closeAll();
        reloadTable(userName)
    }

      function batchRemove(fd) {
          const arr_box = [];
          layui.each(fd,function(index, item) {
              arr_box.push(item.id);
          })
          const deleteUrl = "/api/v1/invoice/" + arr_box.join(",");
          SyncDelete(deleteUrl, null, function (data) {
            if (data.code === 0) {
                layer.msg("删除成功", closeAndReloadTable(null));
            } else {
                layer.msg("删除失败："+data.msg, closeAndReloadTable(null));
            }
        })
          return false;
      }

      function remove(item) {
          const deleteUrl = "/api/v1/invoice/" + item.id;
          SyncDelete(deleteUrl, null, function (data) {
            if (data.code === 0) {
                layer.msg("删除成功", closeAndReloadTable(null));
            } else {
                layer.msg("删除失败："+data.msg, closeAndReloadTable(null));
            }
        })
          return false;
      }

      function batchDownPdf(fd) {
          const arr_box = [];
          layui.each(fd,function(index, item) {
              arr_box.push(item.id);
          })
          const downloadPdfUrl = "/api/v1/invoice/download/pdf/" + arr_box.join(",");

          closeAndReloadTable(null);
          window.open(downloadPdfUrl);
      }

      function batchDownExcel(fd) {
          const arr_box = [];
          layui.each(fd,function(index, item) {
              arr_box.push(item.id);
          })
          const downloadPdfUrl = "/api/v1/invoice/download/excel/" + arr_box.join(",");

          closeAndReloadTable(null);
          window.open(downloadPdfUrl);
      }

    function initGroupDropdownByData(){
        const groupNameUrl = "/api/v1/user-info/groups";
        var groupNameList;
        SyncGet(groupNameUrl, null, function (data) {
            if (data.code === 0) {
                groupNameList = data.data;
            } else {layer.msg("服务异常："+data.msg);
            }
        })

        dropdown.render({
            elem: '#groupNameId'
            ,data: groupNameList
            ,click: function(obj){
                this.elem.val(obj.title);
                initUserInfoDropdownByData(obj.title);
            }
            ,style: 'width: 235px;'
        });
    }

    function initUserInfoDropdownByData(groupName){
        const groupNameUrl = "/api/v1/user-info/users/" + groupName;
        var userInfoList;
        SyncGet(groupNameUrl, null, function (data) {
            if (data.code === 0) {
                userInfoList = data.data;
            } else {layer.msg("服务异常："+data.msg);
            }
        })

        dropdown.render({
            elem: '#userInfoId'
            ,data: userInfoList
            ,click: function(obj){
                this.elem.val(obj.title);
            }
            ,style: 'width: 235px;'
        });
    }
</script>

</body>
</html>